<template>
	<view class="container">
		<uni-forms :modelValue="formData" ref="form" :rules="rules">
			<uni-forms-item label="邮箱" name="email">
				<uni-easyinput  v-model="formData.email" placeholder="请输入邮箱" />
			</uni-forms-item>
			<uni-forms-item label="验证码" name="code"
			class='form_item'>
				<uni-easyinput v-model="formData.code" placeholder="请输入验证码" 
				style="flex: 1;"/>
				<button type="primary" size="mini"
				@click="getCode" :disabled='disabled'>{{getCodeText}}</button>
			</uni-forms-item>
		</uni-forms>
		
		<button type="primary" @click="login">登录</button>
	</view>
</template>

<script>
	const miniupload=uniCloud.importObject('mini-upload')
	const db = uniCloud.database();
	import mixin from '../common/common.mixin.js'
	export default{
		mixins:[mixin],
		data(){
			return {
				formData:{
					email:'',
					code:''
				},
				rules:{},
				disabled:false,
				getCodeText:'获取验证码'
			}
		},
		methods:{
			setTimer(){
				let holdTime = 5,
				_this = this;
				_this.timer=setInterval(()=>{
					if (holdTime <=0) {
						_this.disabled=false
						clearInterval(_this.timer);
						_this.getCodeText = "重新获取验证码"
						return;
					}
					_this.getCodeText =`${holdTime}s后重新获取`
					holdTime--;
				},1000)
			},
			async getCode(){
				if(this.disabled){//禁用
					uni.showToast({
						title:'倒计时结束后再获取',
						icon:'none'
					})
					return
				}
				try{
					let data=await miniupload.sendEmailCode({
						email:this.formData.email,
					})
					console.log(data)
					if(data.result.errCode==0){
						this.disabled=true
						this.setTimer()
						uni.showToast({
							title:'发送成功',
							icon:'none'
						})
					}
				}catch(e){
					console.log(e)
					uni.showToast({
						title:e.errMsg,
						icon:'none'
					})
				}
			},
			login(){
				this.$refs.form.validate().then(res=>{
					console.log('表单数据信息：', res);
					uniCloud.callFunction({
						name:'uni-id-cf',
						data:{
							action:'emailLogin',
							params:{
								email:res.email,
								code:res.code,
								// type:'login'
							}
						},
						success: (e) => {
							console.log(e) // e.result.code==10302 未注册
							if(e.result.errCode==0){
								this.loginSuccess(e.result)
							}else{
								uni.showToast({
									title:e.result.message,
									icon:'none'
								})
							}
						}
					})
				}).catch(err =>{
					console.log('表单错误信息：', err);
				})
			},
		},
		onUnload() {
			clearInterval(this.timer)
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		padding:0 30rpx;
	}
	.form_item {
		& ::v-deep .uni-forms-item__content{
			display: flex;
			align-items: center;
			uni-button{
				margin-left: 20rpx;
			}
		}
	} 
	
</style>
